import Toast, { hideToast } from 'tdesign-miniprogram/toast/index';
import { AreaList, AddAddress, EditAddress } from '../../../../services/address/address';
import util from "../../../../utils/util.js"

const innerNameReg = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$';

Page({
  options: {
    multipleSlots: true,
  },
  externalClasses: ['theme-wrapper-class'],
  data: {
    locationState: {
      name: '',
      mobile: '',
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      districtCode: '',
      districtName: '',
      detail: '',
      isDefault: false,
    },  // 表单
    areaData: [],    // 地区
    areaPickerVisible: false,   // 地区弹窗
    submitActive: false,    // 保存禁选
    verifyTips: ''
  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    if (options.locationState) {
      let locationState = JSON.parse(options.locationState);
      locationState.isDefault = locationState.isDefault === 1 ? true : false;
      locationState.memberAddressId = locationState.id;
      this.setData({ locationState })
      const { isLegal, tips } = this.onVerifyInputLegal();
      this.setData({ submitActive: isLegal, verifyTips: tips })
      this.privateData.verifyTips = tips;
    }
  },

  /* 监听文本 */
  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    if (item === 'address') {
      const { selectedOptions = [] } = e.detail;
      this.setData(
        {
          'locationState.provinceCode': selectedOptions[0].value,
          'locationState.provinceName': selectedOptions[0].label,
          'locationState.cityName': selectedOptions[1].label,
          'locationState.cityCode': selectedOptions[1].value,
          'locationState.districtCode': selectedOptions[2].value,
          'locationState.districtName': selectedOptions[2].label,
          areaPickerVisible: false,
        },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
            verifyTips: tips
          });
          this.privateData.verifyTips = tips;
        },
      );
    } else {
      const { value = '' } = e.detail;
      this.setData({ [`locationState.${item}`]: value },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
            verifyTips: tips
          });
          this.privateData.verifyTips = tips;
        },
      );
    }
  },
  /* 省市区初加载 */
  onPickArea() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '加载中...',
      theme: 'loading',
      direction: 'column',
      duration: -1,
    });
    AreaList({ level: 3 }).then(res => {
      if (res.code === '0000') {
        hideToast({
          context: this,
          selector: '#t-toast',
        });
        this.setData({ areaData: res.data, areaPickerVisible: true })
      }
    })
  },
  /* 设置默认 */
  onCheckDefaultAddress({ detail }) {
    const { value } = detail;
    this.setData({ 'locationState.isDefault': value });
  },
  /* 校验 */
  onVerifyInputLegal() {
    const { name, mobile, detail, districtName } = this.data.locationState;
    const nameRegExp = new RegExp(innerNameReg);
    if (!name || !name.trim()) {
      return {
        isLegal: false,
        tips: '请填写收货人',
      };
    }
    if (!nameRegExp.test(name)) {
      return {
        isLegal: false,
        tips: '收货人仅支持输入中文、英文（区分大小写）、数字',
      };
    }
    if (!mobile || !mobile.trim()) {
      return {
        isLegal: false,
        tips: '请填写手机号',
      };
    }
    if (!util.phoneRegCheck(mobile)) {
      return {
        isLegal: false,
        tips: '请填写正确的手机号',
      };
    }
    if (!districtName || !districtName.trim()) {
      return {
        isLegal: false,
        tips: '请选择省市区信息',
      };
    }
    if (!detail || !detail.trim()) {
      return {
        isLegal: false,
        tips: '请完善详细地址',
      };
    }
    if (detail && detail.trim().length > 50) {
      return {
        isLegal: false,
        tips: '详细地址不能超过50个字符',
      };
    }
    return {
      isLegal: true,
      tips: '',
    };
  },
  /* 保存 */
  formSubmit() {
    const { submitActive } = this.data;
    if (!submitActive) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.privateData.verifyTips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    const { locationState } = this.data;
    locationState.isDefault = locationState.isDefault === true ? 1 : 0
    if (locationState.id) {
      EditAddress(locationState).then(res => {
        if (res.code === '0000') {
          util.showToast("编辑成功", "none", 600)
          setTimeout(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页
            prevPage.setData({ refresh: true });
            wx.navigateBack({ delta: 1 });
          }, 600); 
        }
      })
    } else {
      AddAddress(locationState).then(res => {
        if (res.code === '0000') {
          util.showToast("新增成功", "none", 600)
          setTimeout(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页
            prevPage.setData({ refresh: true });
            wx.navigateBack({ delta: 1 });
          }, 600);
        }
      });
    }
  },
});
